package cn.ssms.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;

import sun.misc.BASE64Encoder;
/**
 * 利用JDK自带的MD5加密
 * 
 * admin=>md5=>加盐md5=>3CA3FD2A0743B4E31CF991B1AE1332BE
 * 
 * @author tangwei
 */

public final class MD5Util {
	public final static String MD5(String s) {
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			byte[] btInput = s.getBytes();
			// 获得MD5摘要算法的 MessageDigest 对象
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			// 使用指定的字节更新摘要
			mdInst.update(btInput);
			// 获得密文
			byte[] md = mdInst.digest();
			// 把密文转换成十六进制的字符串形式
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 加盐MD5<br>
	 * 用于密码处，标准MD5后的值，再进行一次salt md5<br>
	 * 添加字符串为：<br>
	 * 原串长度Base64.encode((s.substring(3, 6) + * "&@zhuang").getBytes()).replaceAll("[\\t\\n\\r]", "").substring(3, 8)
	 * 
	 * @param s
	 * @return
	 */
	public final static String MD5withSalt(String s) {
		String salt = new BASE64Encoder().encode((s.substring(3, 6) + "&@zhuang").getBytes())
				.replaceAll("[\\t\\n\\r]", "").substring(3, 8);
		return MD5Util.MD5(s + salt);
	}
	
	/**
	 * 对文件全文生成MD5摘要
	 * 
	 * @param file  要加密的文件
	 * @return MD5     摘要码
	 */
	public static String MD5(File file) {
		FileInputStream fis = null;
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'A', 'B', 'C', 'D', 'E', 'F' };
		try {
			MessageDigest mdInst = MessageDigest.getInstance("MD5");
			fis = new FileInputStream(file);
			byte[] buffer = new byte[2048];
			int length = -1;
			while ((length = fis.read(buffer)) != -1) {
				mdInst.update(buffer, 0, length);
			}
			byte[] md = mdInst.digest();
			int j = md.length;
			char str[] = new char[j * 2];
			int k = 0;
			for (int i = 0; i < j; i++) {
				byte byte0 = md[i];
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];
				str[k++] = hexDigits[byte0 & 0xf];
			}
			return new String(str);
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		} finally {
			try {
				fis.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

}
